package com.dawn.module.mp.api;

import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.module.mp.api.msgtemplate.MsgTemplateApi;
import com.dawn.module.mp.api.msgtemplate.dto.TemplateMsgSendDTO;
import com.dawn.module.mp.service.msgtemplate.MsgTemplateService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @author cnsu-cmh
 * @date 2024-08-23 20:48
 * @description
 */
@Slf4j
@Service
public class MsgTemplateApiImpl implements MsgTemplateApi {


    @Resource
    @Lazy
    private MsgTemplateService msgTemplateService;


    @Override
    public CommonResult sendTemplateMsg(@Valid TemplateMsgSendDTO form) {
        log.info("发送模板消息开始,参数：{}",form.toString());
        WxMpTemplateMessage.WxMpTemplateMessageBuilder builder = WxMpTemplateMessage.builder()
                .templateId(form.getTemplateId())
                .url(form.getUrl())
                .data(form.getData());
        String[] openidArr = form.getOpenid().split(",");
        for (String openid : openidArr) {
            WxMpTemplateMessage msg = builder.toUser(openid).build();
            msgTemplateService.sendTemplateMsg(msg,form.getAppid());
        }
        log.info("发送模板消息结束");
        return CommonResult.success(openidArr.length);
    }
}
